//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package config_dao

import (
	"context"

	"gitcode.com/eteam/api-server/dao/common"
	"gitcode.com/eteam/proto-gen-go.git/ai_provider_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type LlmProviderInfoDbItem struct {
	ProviderId  string `bson:"_id"`
	Name        string `bson:"name"`
	NeedApiKey  bool   `bson:"needApiKey"`
	DefaultAddr string `bson:"defaultAddr"`
	TimeStamp   int64  `bson:"timeStamp"`
}

func (item *LlmProviderInfoDbItem) ToLlmProviderInfo() *ai_provider_api.LlmProviderInfo {
	return &ai_provider_api.LlmProviderInfo{
		ProviderId:  item.ProviderId,
		Name:        item.Name,
		NeedApiKey:  item.NeedApiKey,
		DefaultAddr: item.DefaultAddr,
	}
}

type _LlmProviderDao struct {
	mc *mongo.Collection
}

func newLlmProviderDao(db *mongo.Database) (*_LlmProviderDao, error) {
	mc := db.Collection(common.DB_NS_CONFIG + "llm_provider")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"timeStamp", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_LlmProviderDao{mc: mc}, nil
}

func (db *_LlmProviderDao) Insert(ctx context.Context, dbItem *LlmProviderInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_LlmProviderDao) Exist(ctx context.Context, providerId string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": providerId})
	return count > 0, err
}

func (db *_LlmProviderDao) Get(ctx context.Context, providerId string) (*LlmProviderInfoDbItem, error) {
	retItem := &LlmProviderInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": providerId}).Decode(retItem)
	return retItem, err
}

func (db *_LlmProviderDao) Remove(ctx context.Context, providerId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": providerId})
	return err
}

func (db *_LlmProviderDao) Update(ctx context.Context, dbItem *LlmProviderInfoDbItem) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": dbItem.ProviderId}, bson.M{"$set": dbItem})
	return err
}

func (db *_LlmProviderDao) List(ctx context.Context) ([]*LlmProviderInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{}, options.Find().SetSort(bson.M{"timeStamp": -1}))
	if err != nil {
		return nil, err
	}
	retList := []*LlmProviderInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}
